package pro1.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import pro1.dao.ModuleMapper;
import pro1.dao.UserMapper;
import pro1.model.User;

import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {
	private static Logger logger = LogManager.getLogger(LoginInterceptor.class);

	@Autowired
	UserMapper userMapper;

	@Autowired
	ModuleMapper moduleMapper;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		if (arg0.getRequestURI().indexOf("/error") < 0) {
			logger.info("uri====" + arg0.getRequestURI());
			logger.info("user====" + arg0.getSession().getAttribute("user"));
		}

		if (arg0.getSession().getAttribute("user") == null) {
			JSONObject obj = new JSONObject();
			arg1.setContentType("application/json; charset=utf-8");
			obj.put("code", 1000);
			obj.put("msg", "未登录");
			PrintWriter writer = arg1.getWriter();
			writer.print(obj.toString());
			writer.close();
			arg1.flushBuffer();
			return false;
		} else {
			User user = (User) arg0.getSession().getAttribute("user");
			String path = arg0.getRequestURI();
			if (user.getRole() == 1) {
				if (moduleMapper.selectByPath(path) != null) {
					if (moduleMapper.selectByUserIdAndPath(user.getId(), path) < 1) {
						JSONObject obj = new JSONObject();
						arg1.setContentType("application/json; charset=utf-8");
						obj.put("code", 2000);
						obj.put("msg", "没有权限");
						PrintWriter writer = arg1.getWriter();
						writer.print(obj.toString());
						writer.close();
						arg1.flushBuffer();
						return false;
					}
				}
			} else {
				if (moduleMapper.selectByPath(path) != null) {
					JSONObject obj = new JSONObject();
					arg1.setContentType("application/json; charset=utf-8");
					obj.put("code", 2000);
					obj.put("msg", "没有权限");
					PrintWriter writer = arg1.getWriter();
					writer.print(obj.toString());
					writer.close();
					arg1.flushBuffer();
					return false;
				}
			}
		}
		return true;
	}

}
